package meterMonitor.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;

public class DESUtils {
    private static Key key;

    private static String KEY_STR = "test-key";

    static {

        try {

            KeyGenerator generator = KeyGenerator.getInstance("DES");

            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");

            secureRandom.setSeed(KEY_STR.getBytes());

            generator.init(secureRandom);

            key = generator.generateKey();

            generator = null;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    public static String encrypt(String str) {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        System.out.println(key);
        System.out.println(key);
        try {
            byte[] bytes = str.getBytes("UTF-8");
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptBytes = cipher.doFinal(bytes);
            return base64Encoder.encode(encryptBytes);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static String decrypt(String str) {
        BASE64Decoder base64Decoder = new BASE64Decoder();
        try {
            byte[] bytes = base64Decoder.decodeBuffer(str);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encryptBytes = cipher.doFinal(bytes);
            return new String(encryptBytes,"UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
